package com.test.system.admin.controller;

import com.test.system.admin.pojo.AdminUser;
import com.test.system.admin.pojo.Menu;
import com.test.system.admin.service.AdminUserService;
import com.test.system.admin.service.MenuService;
import com.test.system.admin.util.AdminConstants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Controller
public class SystemController {
    @Autowired
    private MenuService menuService;

    @RequestMapping("index.html")
    public String index() {
        return "index";
    }

    @RequestMapping("go_login.html")
    public String login() {
        return "login";
    }

    @RequestMapping("error.html")
    public String error() {
        return "error";
    }

    @Autowired
    private AdminUserService adminUserService;

    @RequestMapping("login.html")
    public String login(String email, String password, Model model, HttpSession session) {
//        AdminUser adminUser = adminUserService.doLogin(email, password);
//        if (adminUser == null) {
//            model.addAttribute("message","用户名或密码错误");
//            return "login";
//        }else{
//            session.setAttribute(AdminConstants.SESSION_USER,adminUser);
//        }
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(email, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            model.addAttribute("message", "用户名或密码错误");
            return "login";
        }
        return "index";
    }

    @RequestMapping("side.html")//加载左边菜单
    @ResponseBody
    public Map<String, Object> sideMenu(HttpSession session) {
        //AdminUser adminUser = (AdminUser) session.getAttribute(AdminConstants.SESSION_USER);
        Subject subject = SecurityUtils.getSubject();
        Integer userId = (Integer) subject.getPrincipal();
        List<Menu> menus = menuService.getMenuTree(userId);
        List<String> perms = menuService.getUserPerms(userId);
        Map<String, Object> result = new HashMap<>();
        result.put("menus", menus);
        result.put("perms", perms);
        return result;
    }

    @RequestMapping("logout.html")
    public String logout(HttpSession session) {
        // session.invalidate();
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
